<script setup>
import { defineProps, defineEmits, ref, computed, watch, reactive } from "vue";
import { EyeTwoTone, EyeInvisibleOutlined } from "@ant-design/icons-vue";
import PasswordTips from "@/components/PasswordTips.vue";
import { message } from "ant-design-vue";
import { debounce } from "lodash";
import {sendEmailCode, sendPhoneCode, updateEmail, updatePassword, updatePhone} from "@/api/user.js";
import {getStuInfo} from "@/api/stu.js";
import {userUserStore} from "@/stores/index.js";

// 接收父组件的 props 和 emits
const props = defineProps({
  visible: Boolean,
  fields: {
    type: Array,
    default: () => [],
  },
  title: String,
});

const form = ref()
const emit = defineEmits(["update:visible"]);

// 动态查找 password 类型的字段
const passwordField = computed(() =>
    props.fields.find((field) => field.type === "password")
);
// 用来存储动态生成的表单数据
const model = ref({});

const validatepsd = async (_rules,value) =>{
  if(value === ''){
    return Promise.reject('请输入密码')
  }else {
    return Promise.resolve();
  }
}

//更新学生信息
const updateStuInfo = async () => {
  try{
    const resUserInfo = await getStuInfo();
    if(resUserInfo.date.code === 200){
      userUserStore().setUserInfo(resUserInfo.data.data);
    }else{
      throw new Error(resUserInfo.data.message||'更新信息失败')
    }
  }catch(err){
    message.error(err)
  }
}

//发送验证码逻辑
const isFalse = ref(true)
const isCounting = ref(false);
const count = ref(60);
const sendVerificationCode = async () => {
  // 直接使用 validateField 方法进行邮箱验证
  await form.value.validate(model.value.phoneNum? 'phoneNum':'email').then(async () => {
    if (isCounting.value) return
    isFalse.value = false
    isCounting.value = true
    count.value = 60
    console.log(model.value)
    const res = model.value.phoneNum ? await sendPhoneCode({
      phoneNum: model.value.phoneNum
    }) : await sendEmailCode({
      email: model.value.email
    })
    if(res.data.code === 200){
      message.success('发送成功')
    }else {
      return message.error('发送失败')
    }
    const interval = setInterval(() => {
      count.value--
      if (count.value <= 0) {
        clearInterval(interval)
        isCounting.value = false
      }
    }, 1000)
  }).catch(() => {
    isFalse.value = true
  })
};

// 提交逻辑
const handleSubmit = async () => {
  if(props.title === '换绑手机号') {
    try {
      const res  = updatePhone(model.value)
      if(res.data.code === 200) {
        await updateStuInfo()
        message.success('修改成功')
      }else {
       throw new Error(res.data.message||'修改失败')
      }
    }catch(err) {
      message.error(err)
    }finally {
      handleClose()
    }
  }else if(props.title === '换绑邮箱' ){
    try{
      const res = await updateEmail(model.value)
      if(res.data.code === 200) {
        await updateStuInfo()
        message.success('修改成功')
      }else {
        throw new Error(res.data.message||'验证码发送失败')
      }
    }catch (err) {
      message.error(err)
    }finally {
      handleClose()
    }
  }else if(props.title === '修改密码'){
    try {
      const res = await updatePassword(model.value)
      if(res.data.code === 200) {
        localStorage.clear()
        window.location.href = '/login'
        message.success('修改成功,请重新登录')
      }else {
        throw new Error(res.data.message||'修改失败')
      }
    } catch (err){
      message.error(err)
    }finally {
      handleClose()
    }
  }
};

//监听手机号
watch(() => model.value.phoneNum||model.value.email, async (e) => {
  form.value.validate([e.value]).then(() => {
    isFalse.value = false
  }).catch(() => {
    isFalse.value = true
  })
})

const rules = {
  phoneNum: [
    { required: true, message: '请输入手机号', trigger: 'change' },
    {
      pattern: /^1[3456789]\d{9}$/,
      message: '请输入正确的手机号',
      trigger: 'change'
    }
  ],
  newPassword: [
    { required: true, validator: validatepsd, trigger: 'change' },
    {
      pattern: /^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)(?=.*[!@#$%^&*(),.?":{}|<>_]).{8,20}$/,
      message: '密码必须满足下面的五个条件',
      trigger: 'change'
    }
  ],
  text: [
    { required: true, message: '请输入验证码', trigger: 'change' },
    {
      pattern: /^\d{6}$/,
      message: '请输入6位验证码',
      trigger: 'change'
    }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'change' },
    { pattern: /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/, message: '请输入有效的邮箱地址', trigger: 'change' }
  ],
  verificationCode: [
    { required: true, message: '请输入验证码', trigger: 'change' },
    {
      pattern: /^\d{6}$/,
      message: '请输入6位数字验证码',
      trigger: 'change'
    }
  ]
}

// 关闭弹窗
const handleClose = () => {
  model.value = {}
  emit("update:visible", false);
};
</script>

<template>
  <a-modal
      v-model:open="props.visible"
      :title="props.title"
      :footer="null"
      width="400px"
      @cancel="handleClose"
  >
    <a-form @submit.prevent="handleSubmit"
            ref="form"
            :model="model"
            :rules="rules"
            validateTrigger="change">
      <div v-for="field in props.fields" :key="field.label" style="margin-bottom: 16px;">
        <label>{{ field.label }}</label>
        <!-- 文本输入框 -->
        <a-form-item v-if="field.type === 'text'" :name="field.key">
          <a-input
              v-model:value="model[field.key]"
              style="height: 32px"
              :placeholder="field.placeholder"
          >
            <template #suffix>
              <a-button type="link" @click="sendVerificationCode" :disabled="isCounting||isFalse">
                {{ isCounting ? `${count}秒后重发` : '发送验证码' }}
              </a-button>
            </template>
          </a-input>
        </a-form-item>
        <a-form-item  v-else-if="field.type === 'phone'" name="phoneNum">
          <!-- 手机号输入框 -->
          <a-input
              v-model:value="model.phoneNum"
              :placeholder="field.placeholder"
          />
        </a-form-item>
        <!-- 邮箱输入框 -->
        <a-form-item v-else-if="field.type === 'email'" name="email">
          <a-input
              v-model:value="model.email"
              :placeholder="field.placeholder"
          />
        </a-form-item>
        <a-form-item v-else-if="field.type === 'password'" :name="field.key">
          <!-- 密码输入框 -->
          <a-input-password
              v-model:value="model[field.key]"
              :placeholder="field.placeholder"
          >
            <template #iconRender="v">
              <EyeTwoTone v-if="v"></EyeTwoTone>
              <EyeInvisibleOutlined v-else></EyeInvisibleOutlined>
            </template>
          </a-input-password>
        </a-form-item>
      </div>
      <a-button type="primary" htmlType="submit" block>提交</a-button>
    </a-form>
    <PasswordTips v-if="passwordField" v-model:password="model.password" />
  </a-modal>
</template>

<style scoped>
form label {
  display: block;
  margin-bottom: 8px;
  font-weight: bold;
}
</style>
